package top.rainf.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author 星环
 * @date 2023/5/24 2:40:57
 * @description
 */
@Slf4j
public class FileUtil {
    public static String projectAbsPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    public static final String postImageSavePath = "src/main/resources/webapp/rainf/img/postImages/";
    public static final String avatarImageSavePath = "src/main/resources/webapp/rainf/img/avatar/";
    public static final String webPath = "http://localhost:8080/";
    static {
        projectAbsPath = projectAbsPath.substring(0,projectAbsPath.lastIndexOf("target"));
    }
    public static String saveFileTo(MultipartFile file, String path, String suffix, HttpServletRequest request){
        File dest = null;
        try {
            StringBuilder fullpath =new StringBuilder();
            fullpath.append(projectAbsPath);
            log.info("res={}",fullpath);
            fullpath.append(path).append("/").append(file.getOriginalFilename()).insert(fullpath.lastIndexOf("."),suffix);

            dest = new File(fullpath.toString());
            log.info("保存文件{}到路径{}",file.getOriginalFilename(),dest.getPath());
            byte[] bytes = file.getBytes();
            log.info(dest.getPath());//fuxiang 前2
            String substring = dest.getPath().substring(dest.getPath().lastIndexOf("\\"));
            String pathname = request.getSession().getServletContext().getRealPath("/img/avatar") + substring;
            System.out.println(request.getSession().getServletContext().getRealPath(""));
            File temp = new File(pathname);

            log.info("也存在了 " + pathname);
            FileOutputStream fout = new FileOutputStream(temp);
            fout.write(bytes);
            fout.flush();
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String webRoot = dest.getPath().substring(dest.getPath().indexOf("img"));
        log.info("webroot:{}",webRoot);
        String webPath = FileUtil.webPath + webRoot;
        String ret = webPath.replaceAll("\\\\", "/");
        log.info("final -> {}",ret);
        return ret;
    }

    public static String getRandomSuffix(){
        return "-"+String.valueOf((int)(Math.random()*10));
    }
}
